package com.fancon.android.gardenjokesx.widget;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.fancon.android.core.IFanconGlobalState;
import com.fancon.android.emoji.widget.RichTextView;
import com.fancon.android.gardenjokesx.R;
import com.fancon.android.gardenjokesx.activity.FollowxActivity;
import com.fancon.android.gardenjokesx.activity.M05Activity;
import com.fancon.android.gardenjokesx.activity.PhotoDetailActivity;
import com.fancon.android.gardenjokesx.activity.ProfileActivity;
import com.fancon.android.gardenjokesx.dialog.M04_5Dialog;
import com.fancon.android.gardenjokesx.dialog.M04_6Dialog;
import com.fancon.android.gardenjokesx.dialog.UserReportingDialog;
import com.fancon.android.gardenjokesx.entity.Photo;
import com.fancon.android.gardenjokesx.entity.ReportErrors;
import com.fancon.android.gardenjokesx.entity.User;
import com.fancon.android.gardenjokesx.rpc.GardenJokesApiConnect;
import com.fancon.android.gardenjokesx.rpc.JsonPaser;
import com.fancon.android.gardenjokesx.utils.Constant;
import com.fancon.android.gardenjokesx.utils.StringUtil;
import com.fancon.android.gardenjokesx.utils.TimeUtil;
import com.fancon.android.gardenjokesx.utils.UserUtil;
import com.fancon.android.multithread.RequestUI;
import com.fancon.android.ui.widget.ImageCacheView;
/**
 * 
 * @author binhbt
 * 2012
 */
public class JokeDetailHeader extends LinearLayout implements OnClickListener {
	private Context mContext;
	private ImageCacheView img;
	private ImageCacheView avatar;
	private RichTextView caption;
	private TextView userName, friends, timePost, totalLike, totalComment;
	private Button likeBtn, commentBtn, shareBtn, reportBtn;
	private ImageButton photoOptionBtn;
	private String currentUserId;
	private Photo mPhoto;
	private DetailTopControlView topControl;

	// private String lastSaveName = "";

	public JokeDetailHeader(Context context) {
		super(context);
		mContext = context;
		// TODO Auto-generated constructor stub
		LayoutInflater layoutInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		layoutInflater.inflate(R.layout.joke_detail_infox, this);
		User user = UserUtil.getInfoUserLogin(mContext);
		currentUserId = user.getUser_id();
		avatar = (ImageCacheView) findViewById(R.id.jokes_detail_avatar);
		img = (ImageCacheView) findViewById(R.id.cm_listphotos_imageview);
		caption = (RichTextView) findViewById(R.id.comment);
		userName = (TextView) findViewById(R.id.cm_listphotos_userName);
		timePost = (TextView) findViewById(R.id.cm_listphotos_timepost);
		totalLike = (TextView) findViewById(R.id.cm_listphotos_totalLike);
		totalComment = (TextView) findViewById(R.id.cm_listphotos_totalComment);
		likeBtn = (Button) findViewById(R.id.cm_listphotos_btnLike);
		commentBtn = (Button) findViewById(R.id.cm_listphotos_btnComment);
		photoOptionBtn = (ImageButton) findViewById(R.id.cm_listphotos_btnPhotoOption);
		friends = (TextView) findViewById(R.id.cm_listphotos_withUser);

		avatar.setOnClickListener(this);
		userName.setOnClickListener(this);
		totalLike.setOnClickListener(this);
		likeBtn.setOnClickListener(this);
		commentBtn.setOnClickListener(this);
		photoOptionBtn.setOnClickListener(this);
		img.setOnClickListener(this);
	}
	public JokeDetailHeader(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		// TODO Auto-generated constructor stub
		LayoutInflater layoutInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		layoutInflater.inflate(R.layout.joke_detail_infox, this);
		User user = UserUtil.getInfoUserLogin(mContext);
		currentUserId = user.getUser_id();
		avatar = (ImageCacheView) findViewById(R.id.jokes_detail_avatar);
		img = (ImageCacheView) findViewById(R.id.cm_listphotos_imageview);
		caption = (RichTextView) findViewById(R.id.comment);
		userName = (TextView) findViewById(R.id.cm_listphotos_userName);
		timePost = (TextView) findViewById(R.id.cm_listphotos_timepost);
		totalLike = (TextView) findViewById(R.id.cm_listphotos_totalLike);
		totalComment = (TextView) findViewById(R.id.cm_listphotos_totalComment);
		likeBtn = (Button) findViewById(R.id.cm_listphotos_btnLike);
		commentBtn = (Button) findViewById(R.id.cm_listphotos_btnComment);
		photoOptionBtn = (ImageButton) findViewById(R.id.cm_listphotos_btnPhotoOption);
		friends = (TextView) findViewById(R.id.cm_listphotos_withUser);

		avatar.setOnClickListener(this);
		userName.setOnClickListener(this);
		totalLike.setOnClickListener(this);
		likeBtn.setOnClickListener(this);
		commentBtn.setOnClickListener(this);
		photoOptionBtn.setOnClickListener(this);
		img.setOnClickListener(this);
	}
	public void loadContent(Photo photo) {
		try {
			if (photo != null) {
				mPhoto = photo;
				avatar.loadImage(StringUtil.processImageLink(photo.getUser()
						.getUrl_image()), true);
				if (!photo.getUrl_photo().equals(Constant.NO_COMIC)) {
					img.loadImage(StringUtil.processImageLink(photo
							.getUrl_photo()));
				} else {
					img.setVisibility(View.GONE);
				}
				try {
					caption.setText(URLDecoder.decode(photo.getCaption(),
							"UTF-8"));
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				userName.setText(photo.getUser().getUser_name());
				timePost.setText(TimeUtil.getTimeCount(photo.getTime_post(),
						mContext));
				totalLike.setText(StringUtil.getPostCount(photo
						.getNumber_click()));
				totalComment.setText(StringUtil.getPostCount(photo
						.getNumber_comment()));
				// likebtn
				if (photo.isIs_clicked() == true) {
					likeBtn.setBackgroundResource(R.drawable.m03_btnlike_checked);
					likeBtn.setTextColor(mContext.getResources().getColor(
							R.color.white));
					if (topControl != null) {
						topControl.like();
					}
				} else {
					likeBtn.setBackgroundResource(R.drawable.m03_btnlike);
					likeBtn.setTextColor(mContext.getResources().getColor(
							R.color.m03_text_orange));
				}
				// Button comment
				if (photo.isIs_commented() == true) {
					commentBtn.setBackgroundResource(R.drawable.m03_btncomment);
					commentBtn.setTextColor(mContext.getResources().getColor(
							R.color.white));
				} else {
					commentBtn
							.setBackgroundResource(R.drawable.m03_btncomment_0);
					commentBtn.setTextColor(mContext.getResources().getColor(
							R.color.m03_text_blue));
				}

				// for with friends
				try {
					friends.setText("");
					if (photo.getFriend() != null
							&& photo.getFriend().size() > 0) {
						for (int i = 0; i < photo.getFriend().size(); i++) {
							final String userNameFriend = photo.getFriend()
									.get(i).getUser_name();
							final String userIDFriend = photo.getFriend()
									.get(i).getUser_id();

							String word;
							if (i != 0) {
								word = ", " + userNameFriend;
							} else {
								word = userNameFriend;
							}

							if (!userIDFriend.equals("-1")) {
								Spannable WordSpan = new SpannableString(word);
								WordSpan.setSpan(
										new StringUtil.NonUnderlinedClickableSpan() {
											@Override
											public void onClick(View widget) {
												Intent intent = new Intent(
														mContext,
														ProfileActivity.class);
												intent.putExtra(
														Constant.USER_ID_VIEW,
														userIDFriend);
												mContext.startActivity(intent);
											}
										},
										word.length() - userNameFriend.length(),
										word.length(),
										Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

								WordSpan.setSpan(
										new ForegroundColorSpan(
												mContext.getResources()
														.getColor(
																R.color.common_text_isclick)),
										0, word.length(),
										Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
								friends.append(WordSpan);
							} else {
								Spannable WordSpanNoClick = new SpannableString(
										URLDecoder.decode(word, "UTF-8"));
								WordSpanNoClick
										.setSpan(
												new ForegroundColorSpan(
														mContext.getResources()
																.getColor(
																		R.color.black)),
												word.length()
														- userNameFriend
																.length(),
												word.length(),
												Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
								friends.append(WordSpanNoClick);
							}
						}
						friends.setMovementMethod(LinkMovementMethod
								.getInstance());
						// bundle.putString(Constant.TAGGED_FRIEND,
						// holder.cm_listphotos_withUser.getText().toString());
					}
				} catch (Exception e) {
					e.printStackTrace();
					// TODO: handle exception
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
	}

	public void doLike() {
		// likebtn
		if (mPhoto.isIs_clicked() != true) {
			likeBtn.setBackgroundResource(R.drawable.m03_btnlike_checked);
			likeBtn.setTextColor(mContext.getResources()
					.getColor(R.color.white));
			if (topControl != null) {
				topControl.like();
			}
			mPhoto.setNumber_click(mPhoto.getNumber_click() + 1);
			totalLike
					.setText(StringUtil.getPostCount(mPhoto.getNumber_click()));
		} else {
			likeBtn.setBackgroundResource(R.drawable.m03_btnlike);
			likeBtn.setTextColor(mContext.getResources().getColor(
					R.color.m03_text_orange));
			if (topControl != null) {
				topControl.unLike();
			}
			mPhoto.setNumber_click(mPhoto.getNumber_click() - 1);
			totalLike
					.setText(StringUtil.getPostCount(mPhoto.getNumber_click()));
		}
		//Update to global storage
		mPhoto.setIs_clicked(!mPhoto.isIs_clicked());
		((IGlobalStorage)(((Activity)(mContext)).getApplication())).setCurrentPhoto(mPhoto);
		((IGlobalStorage)(((Activity)(mContext)).getApplication())).setChange(true);
		//
		LikeRequest req = new LikeRequest("like_req", (Activity) mContext);
		((IFanconGlobalState) mContext).getRequestQueue().addRequest(req);
	}

	private void doShare() {
		// if (lastSaveName == "") {
		// AlertDialog.Builder alert = new AlertDialog.Builder(mContext);
		// alert.setTitle(R.string.select_name);
		// final EditText input = new EditText(mContext);
		// alert.setView(input);
		// alert.setPositiveButton(getResources().getString(R.string.ok),
		// new DialogInterface.OnClickListener() {
		// public void onClick(DialogInterface dialog,
		// int whichButton) {
		// doSave(input.getText().toString(), true);
		// }
		// });
		//
		// alert.setNegativeButton(getResources().getString(R.string.cancel),
		// new DialogInterface.OnClickListener() {
		// public void onClick(DialogInterface dialog,
		// int whichButton) {
		// }
		// });
		//
		// alert.show();
		// } else {
		// doSave(lastSaveName, true);
		// }
	}

	private void doReport() {
		UserReportingDialog reportJorke = new UserReportingDialog(mContext,
				mPhoto.getUser().getUser_id(), false);
		reportJorke.show();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == avatar || v == userName) {
			Intent intent = new Intent(mContext, ProfileActivity.class);
			intent.putExtra(Constant.USER_ID_VIEW, mPhoto.getUser()
					.getUser_id());
			mContext.startActivity(intent);
		} else if (v == likeBtn) {
			doLike();
		} else if (v == commentBtn) {
			Intent intent = new Intent(mContext, M05Activity.class);
			intent.putExtra(Constant.PHOTO_ID, mPhoto.getPhoto_id());
			intent.putExtra("viewed_user_id", mPhoto.getUser().getUser_id());
			intent.putExtra(Constant.SCREEN_ID, Constant.M03_1);
			mContext.startActivity(intent);
		} else if (v == photoOptionBtn) {
			if ((!currentUserId.equals(mPhoto.getUser().getUser_id()))&&(!currentUserId.equals("ea70f3af-aeff-4bbe-839a-a50854fdbcae"))) {
				final Bundle b = new Bundle();
				M04_5Dialog M045dialog = new M04_5Dialog(mContext,
						(Activity) mContext, mPhoto, b);
				M045dialog.show();
			} else {
				final Bundle b = new Bundle();
				M04_6Dialog M046dialog = new M04_6Dialog(mContext,
						(Activity) mContext, mPhoto, b);
				M046dialog.show();
			}
		} else if (v == totalLike) {
			Intent intent = new Intent(mContext, FollowxActivity.class);
			intent.putExtra(Constant.PHOTO_ID, mPhoto.getPhoto_id());
			intent.putExtra(Constant.SCREEN_ID, Constant.M03_1);
			mContext.startActivity(intent);
		} else if (v == shareBtn) {
			doShare();
		} else if (v == reportBtn) {
			doReport();
		}else if(v == img){
			Intent intent = new Intent(mContext, PhotoDetailActivity.class);
			intent.putExtra("photoUrl", StringUtil.processImageLink(mPhoto.getUrl_photo()));
			mContext.startActivity(intent);
		}
	}

	public class LikeRequest extends RequestUI {
		private ReportErrors report;

		public LikeRequest(Object key, Activity activity) {
			super(key, activity);
		}

		@Override
		public void execute() throws Exception {

			List<NameValuePair> photoIdAndUserId = new ArrayList<NameValuePair>(
					2);
			photoIdAndUserId.add(new BasicNameValuePair("user_id",
					currentUserId));
			photoIdAndUserId.add(new BasicNameValuePair("photo_id", mPhoto
					.getPhoto_id()));

			GardenJokesApiConnect api = new GardenJokesApiConnect(mContext);
			String request = api.execGet(mContext,
					GardenJokesApiConnect.GROUP_M,
					mPhoto.isIs_clicked() ? "cancelLikePhoto" : "buttonClick",
					photoIdAndUserId);
			Log.v("LIKE Request", request);
			JsonPaser json = new JsonPaser();
			report = json.getReport(request);
		}

		@Override
		public void executeUI(Exception ex) {
			if (report != null && !report.isIs_success()) {
				// Toast.makeText(mContext,
				// mContext.getString(R.string.like_fail), 1000).show();
				// reset to original
				if (mPhoto.isIs_clicked() == true) {
					likeBtn.setBackgroundResource(R.drawable.m03_btnlike_checked);
					likeBtn.setTextColor(mContext.getResources().getColor(
							R.color.white));
					if (topControl != null) {
						topControl.like();
					}
					mPhoto.setNumber_click(mPhoto.getNumber_click() + 1);
					totalLike.setText(StringUtil.getPostCount(mPhoto
							.getNumber_click()));
				} else {
					likeBtn.setBackgroundResource(R.drawable.m03_btnlike);
					likeBtn.setTextColor(mContext.getResources().getColor(
							R.color.m03_text_orange));
					if (topControl != null) {
						topControl.unLike();
					}
					mPhoto.setNumber_click(mPhoto.getNumber_click() - 1);
					totalLike.setText(StringUtil.getPostCount(mPhoto
							.getNumber_click()));
				}
				
				//Update to global storage
				mPhoto.setIs_clicked(!mPhoto.isIs_clicked());
				((IGlobalStorage)(((Activity)(mContext)).getApplication())).setCurrentPhoto(mPhoto);
				((IGlobalStorage)(((Activity)(mContext)).getApplication())).setChange(true);
			} else {
				// Toast.makeText(mContext,
				// mContext.getString(R.string.like_success), 1000).show();
//				mPhoto.setIs_clicked(!mPhoto.isIs_clicked());
//				((IGlobalStorage)(((Activity)(mContext)).getApplication())).setCurrentPhoto(mPhoto);
//				((IGlobalStorage)(((Activity)(mContext)).getApplication())).setChange(true);
			}
		}

	}

	public DetailTopControlView getTopControl() {
		return topControl;
	}

	public void setTopControl(DetailTopControlView topControl) {
		this.topControl = topControl;
	}

}
